How to insert text at the beginning and end of a specified line?

I would like to insert text at the beginning and at the end of the specified line of the number, for example, I have this txt file:

apple banana orange pineapple 

To insert at the beginning and end of the first line, I use:

 while read -r line do sed "1i[text_insert]$line" > outputfile1 done < inputfile while read -r line do sed "1i$line[text_insert2]" > outputfile2 done < outputfile1 

and I get:

 [text_insert]apple[text_insert2] banana orange pineapple 

And now I would like to add text to line number 2:

 [text_insert]apple[text_insert2] [text_insert3]banana[text_insert4] orange pineapple 

I tried to use the same thing, but this does not work, and all the other features that I found are to insert text as a new line before the specified line, and not add it to the specified line.

+4
source share
4 answers

Try the following snippet:

 sed '2s/.*/[text_insert] & [text_insert2]/' file.txt 

& have special meaning: this is the matching part from the left side of the s/// substitution

Example:

 $ cat file.txt a b c $ sed '2s/.*/[text_insert] & [text_insert2]/' file.txt a [text_insert] b [text_insert2] c 
0
source

With awk :

 $ line=3 $ awk -v num=$line 'NR==num{$0="[Insert New Text] " $0 " [Insert End Text]"}1' file apple banana [Insert New Text] orange [Insert End Text] pineapple 
+1
source

You can use awk to accomplish what you need with the built-in NR variable. For instance:

 #!/usr/bin/awk -f { if (NR == 1) printf("[text_insert] %s [text_insert2]\n", $0) else if (NR == 2) printf("[text_insert3] %s [text_insert4]\n", $0) else print $0 } 
0
source

If awk is an option:

 $ cat file.txt a b c $ awk 'NR==2{printf "[text_insert] %s [text_insert2]\n", $0;next}1' file.txt a [text_insert] b [text_insert2] c 
0
source

Source: https://habr.com/ru/post/1486334/


All Articles