Re: Insert text before the first word in all the lines of a file (301 Views)
Reply
Regular Advisor
Posts: 131
Registered: ‎08-25-2003
Message 1 of 8 (301 Views)
Accepted Solution

Insert text before the first word in all the lines of a file

Hi,

I have a file and I want to insert a text say "abcd" before the first word in all the lines of the file without opening the file. For example, the input file is something like

1234 5678 90001
1111 1111 11111

The ouput file should be like

abcd 1234 5678 90001
abcd 1111 1111 11111


Can anyone please help me out in this.

Thanks,
Anand
Honored Contributor
Posts: 508
Registered: ‎12-11-2004
Message 2 of 8 (301 Views)

Re: Insert text before the first word in all the lines of a file

$ cat input_file | sed 's/^/abcd /g' > outfile

- Biswajit
:-)
Honored Contributor
Posts: 6,591
Registered: ‎05-19-2003
Message 3 of 8 (301 Views)

Re: Insert text before the first word in all the lines of a file

A perl solution is of course realy tight also:

> cat > x
1234 5678 90001
1111 1111 11111
> perl -pe '$_="abcd $_"' x
abcd 1234 5678 90001
abcd 1111 1111 11111

Cheers,
Hein.

(0 points please :-)
Esteemed Contributor
Posts: 360
Registered: ‎08-21-1997
Message 4 of 8 (301 Views)

Re: Insert text before the first word in all the lines of a file

Or in ex/vi:


:1,$s/^/abcd /


Mic
What kind of a name is 'Wolverine'?
Honored Contributor
Posts: 1,079
Registered: ‎01-29-2004
Message 5 of 8 (301 Views)

Re: Insert text before the first word in all the lines of a file

Hi Anand,

Open the file using vi.

do the following.

:%s/^/word to be inserted/g


regards,
Syam
Honored Contributor
Posts: 1,264
Registered: ‎11-15-2000
Message 6 of 8 (301 Views)

Re: Insert text before the first word in all the lines of a file

[root@iris ~]# cat sample
one 1
two 1 two 1
three 1
one 1
two 1
two 1
three 1
hello world
[root@iris ~]# sed 's/^/abcd /' sample
abcd one 1
abcd two 1 two 1
abcd three 1
abcd one 1
abcd two 1
abcd two 1
abcd three 1
abcd hello world
Occasional Contributor
Posts: 5
Registered: ‎01-14-2005
Message 7 of 8 (301 Views)

Re: Insert text before the first word in all the lines of a file

You can use perl inplace editing option

$ perl -i.old -pe 's/^/abcd /' a
$ cat a
abcd 1234 5678 90001
abcd 1111 1111 11111
$
Advisor
Posts: 18
Registered: ‎07-01-2001
Message 8 of 8 (301 Views)

Re: Insert text before the first word in all the lines of a file

sed 's/^/abcd /' input_file > output_file
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.