Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

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

SOLVED
Go to Solution
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
Honored Contributor Honored Contributor

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 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 :-)
Esteemed Contributor 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'?
Honored Contributor 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
Honored Contributor 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
Highlighted
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
$
Advisor

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

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