Operating System - HP-UX
1752796 Members
5683 Online
108789 Solutions
New Discussion юеВ

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

 
SOLVED
Go to solution
Anand_30
Regular Advisor

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
7 REPLIES 7
Biswajit Tripathy
Honored Contributor
Solution

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

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

- Biswajit
:-)
Hein van den Heuvel
Honored Contributor

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 :-)
Mic V.
Esteemed Contributor

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'?
Ranjith_5
Honored Contributor

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
twang
Honored Contributor

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
Sundaram Ramasamy
Occasional Contributor

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
$
Bob Smith_23
Advisor

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

sed 's/^/abcd /' input_file > output_file