What GNU/Linux command-line tool would I use for performing a search and replace on a file?

后端 未结 4 2079
南方客
南方客 2021-02-07 00:10

What GNU/Linux command-line tool would I use for performing a search and replace on a file?

Can the search text, and replacement, be specified in a regex format?

4条回答
  •  无人及你
    2021-02-07 00:37

    sed 's/a.*b/xyz/g;' old_file > new_file
    

    GNU sed (which you probably have) is even more versatile:

    sed -r --in-place 's/a(.*)b/x\1y/g;' your_file
    

    Here is a brief explanation of those options:

    -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied)

    -r, --regexp-extended use extended regular expressions in the script.

    The FreeBSD version also supports these options. The NetBSD and OpenBSD versions support only -r.

    If you want to learn more about sed, Cori has suggested this tutorial.

提交回复
热议问题