![]() ![]() This is one way to add some text to the end of the first line of a file sed -e '1s/$/new text/' yourfile.txt I want just to edit first line of file by appending something to the first line and rest is same.How should I achieve it? The head tail combination will not work if the file has lesser number of lines than 'n' and what about if you want to extract a line. But for example if you wanted to read ONLY line 5 from a file you could do $ head -n 5 | tail -n 1 I'm not sure if it is more or less complicated ) Please see the blog entry Īnother way to do it is with head and tail. So what if I had a huge file and I wanted to extract, say, every 4th line? Useful sed tricks to customize configuration files.Extract columns and fields from text files.Use sed or perl to extract every nth line in a text file.If you know some different ways to extract lines in a file, please share with us by filling out a comment. What if the lines you want to extract are not in sequence, say lines 1 to 2, and line 4? Note that the comma specifies a range (from the line before the comma to the line after). To extract a range of lines, say lines 2 to 4, you can execute either of the following: Otherwise, the !d will bring back the last command you executed that starts with the letter d. Note that the single quotes are necessary. ![]() '1!d' means if a line is not(!) the first line, delete. To fix it, you need to suppress the default output (using -n), making explicit prints the only way to print to default output.Īlternatively, you can tell sed to delete all but the first line. The explicit 1p command just tells it to print the first line. Why? The default output behavior is to print every line of the input file stream. Note that it prints the whole file, with the first line printed twice. My first attempt uses the p sed command (for print): So, let's try extracting lines using sed: the stream editor. This specific task can be easily done with this:įor a more complicated task, like extract the second to third lines of a file. Yesterday, I needed to extract the first line of a file, say named somefile.txt. If you write bash scripts a lot, you are bound to run into a situation where you want to extract some lines from a file.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |