Sed, string editor _ Add line number

In general, the way sed works is that it is given either a single editing command (on the command line) or the name of a script file containing multiple commands, and it then performs these commands upon each line in the stream of text.

sed is a very capable program, able to perform fairly complex editing tasks to streams of text. It is most often used for simple, one-line tasks rather than long scripts.

1. print out specific lines in a file :

sed -n '3, 10p'  text_name.txt

### print out the lines from 3 to 10 of file 'text_name.txt'

sed -n '12, 18!p' text_name.txt

### print out the lines in file text_name.txt except that of 12 to 18 lines;

2. search and replace in a file:

sed '/s/old_string/new_string/g'    filename.txt

b). default to  replace the 1st one string found in each line of a file:

sed 's/old_string/new_string'   filename.txt

example:

$ echo -e "front 1 front and back\nthe front 2 national front"|sed 's/front/back/'

back 1 front and back

the back 2 national front

3. search and replace in a specific line:

sed 'Ns/old_string/new_string/'       file_name    ###replace the 1st one matched in line N

sed 'Ns/old_string/new_string/g'    file_name    ### replace all the matched strings in line N

4. delete lines of a file, but not modify the original file:

sed '13,14d' file_name

5. Use 'sed -i ' to modify file, and save it;

sed -i '5s/:/:\"/' awk_prog_script0.txt

sed -i '5s/The/\"The/' awk_prog_script0.txt

6. Add line number  to a .txt file

  sed '/./=' file_name.txt | sed 'N; s/\n/\t/' file_name.txt

If using 'awk':

       $ awk '{print NR, $0}' t1.txt >> t1_LNum.txt

### NR, number of record for each line, that is the 'line number'

### $0, the entire line content

Sed, string editor _ Add line number_第1张图片
add line number to each line



Sed, string editor _ Add line number_第2张图片
Sed, string editor _ Add line number_第3张图片

你可能感兴趣的:(Sed, string editor _ Add line number)