In this sed article, we will see how to read a file into a sed output, and also how to write a section of a file content to a different file.
Let us assume we have 2 files, file1 and file2 with the following content:
$ cat file1 1apple 1banana 1mango
$ cat file2 2orange 2strawberrysed has 2 options for reading and writing:
r filename : To read a file name content specified in the filename
w filename : To write to a file specified in the filename
Let us see some examples now:
1. Read the file2 after every line of file1.
$ sed 'r file2' file1 1apple 2orange 2strawberry 1banana 2orange 2strawberry 1mango 2orange 2strawberryr file2 reads the file contents of file2. Since there is no specific number before 'r', it means to read the file contents of file2 for every line of file1. And hence the above output.
2. The above output is not very useful. Say, we want to read the file2 contents after the 1st line of file1:
$ sed '1r file2' file1 1apple 2orange 2strawberry 1banana 1mango'1r' indicates to read the contents of file2 only after reading the line1 of file1.
3. Similarly, we can also try to read a file contents on finding a pattern:
$ sed '/banana/r file2' file1 1apple 1banana 2orange 2strawberry 1mangoThe file2 contents are read on finding the pattern banana and hence the above output.
4. To read a file content on encountering the last line:
$ sed '$r file2' file1 1apple 1banana 1mango 2orange 2strawberryThe '$' indicates the last line, and hence the file2 contents are read after the last line. Hey, hold on. The above example is put to show the usage of $ in this scenario. If your requirement is really something like above, you need not use sed. cat file1 file2 will do :) .
Let us now move onto the writing part of sed. Consider a file, file1, with the below contents:
$ cat file1 apple banana mango orange strawberry
1. Write the lines from 2nd to 4th to a file, say file2.
$ sed -n '2,4w file2' file1The option '2,4w' indicates to write the lines from 2 to 4. What is the option "-n" for? By default, sed prints every line it reads, and hence the above command without "-n" will still print the file1 contents on the standard output. In order to suppress this default output, "-n' is used. Let us print the file2 contents to check the above output.
$ cat file2 banana mango orangeNote: Even after running the above command, the file1 contents still remain intact.
2. Write the contents from the 3rd line onwards to a different file:
$ sed -n '3,$w file2' file1 $ cat file2 mango orange strawberryAs explained earlier, the '3,$' indicates from 3 line to end of the file.
3. To write a range of lines, say to write from lines apple through mango :
$ sed -n '/apple/,/mango/w file2' file1 $ cat file2 apple banana mango