sed

#sed

# 文件中第6行插入一行
sed -i '6i this is the new line' test.txt
sed -i 's/原始内容/替换内容/\$' 文件名
#替换文件中第6行
sed -i '6s/.*/替换内容/'
sed -n '\$p' 文件名
# 删除文件中的第4行到文件尾
sed -i '4,\$d' 文件名
# 删除空行
sed  '/^&/d' 文件名

sed (stream editor) is a powerful command-line utility used for parsing and transforming text in a stream or file. Here is a summary of common sed usage and commands:

Basic Usage

sed [options] 'script' [file...]

Common Options

Addressing

sed commands can be restricted to specific lines or ranges of lines:

Commands

Examples

  1. Print specific lines:

    sed -n '5p' file.txt  # Print the 5th line
    sed -n '5,10p' file.txt  # Print lines 5 to 10
    
  2. Substitute text:

    sed 's/foo/bar/' file.txt  # Replace first occurrence of 'foo' with 'bar' in each line
    sed 's/foo/bar/g' file.txt  # Replace all occurrences of 'foo' with 'bar' in each line
    
  3. Delete lines:

    sed '3d' file.txt  # Delete the 3rd line
    sed '/^$/d' file.txt  # Delete all empty lines
    
  4. Insert and append text:

    sed '3i\Inserted text' file.txt  # Insert text before the 3rd line
    sed '3a\Appended text' file.txt  # Append text after the 3rd line
    
  5. Extract a block of text:

    sed -n '/start/,/end/p' file.txt  # Print lines from 'start' to 'end'
    
  6. In-place editing:

    sed -i 's/foo/bar/g' file.txt  # Replace 'foo' with 'bar' directly in the file
    sed -i.bak 's/foo/bar/g' file.txt  # Same as above but create a backup with .bak extension
    
  7. Using multiple commands:

    sed -e 's/foo/bar/' -e '/baz/d' file.txt  # Substitute and delete in one command
    

Special Characters

Escaping Characters

Characters like /, &, and \ have special meanings in sed and must be escaped with a backslash (\) if they are to be used literally.

By mastering these sed commands and techniques, you can efficiently manipulate and transform text in a variety of powerful ways directly from the command line.