GNU/Linux >> Linux の 問題 >  >> Ubuntu

複数のファイルテキストをSedに置き換えますか?

テキストファイルの一部のテキストをsedに置き換えようとしています しかし、複数のファイルでそれを行う方法がわかりません。
私が使用するもの:

sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g /path/to/file/target_text_file

複数のファイルを使用する前に、次のコマンドを使用して、対象のテキストファイルのパスをテキストファイルに出力しました。

find /path/to/files/ -name "target_text_file" > /home/user/Desktop/target_files_list.txt

sedを実行したい target_files_list.txtによると 。

承認された回答:

while ... doを使用してファイルをループできます ループ:

$ while read i; do printf "Current line: %s\n" "$i"; done < target_files_list.txt

あなたの場合、printf ...を置き換える必要があります sedを使用 必要なコマンド。

$ while read i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt

ただし、findだけを使用して目的を達成できることに注意してください。 :

$ find /path/to/files/ -name "target_text_file" -exec sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' {} \;

-execについて詳しく読むことができます man find | less '+/-exec '

   -exec command ;

          Execute command; true if 0 status is returned.  All
          following arguments to find are taken to be arguments to
          the command until an argument consisting of `;' is
          encountered.  The string `{}' is replaced by the current
          file name being processed everywhere it occurs in the
          arguments to the command, not just in arguments where it
          is alone, as in some versions of find.  Both of these
          constructions might need to be escaped (with a `\') or
          quoted to protect them from expansion by the shell.  See
          the EXAMPLES section for examples of the use of the
          -exec option.  The specified command is run once for
          each matched file.  The command is executed in the
          starting directory.  There are unavoidable security
          problems surrounding use of the -exec action; you should
          use the -execdir option instead.

編集:

コメントでユーザーのterdonとdessertが正しく指摘しているように、
-rを使用する必要があります read
バックスラッシュを正しく処理するためです。 shellcheckによっても報告されます :

$ cat << EOF >> do.sh
#!/usr/bin/env sh
while read i; do printf "$i\n"; done < target_files_list.txt
EOF
$ ~/.cabal/bin/shellcheck do.sh

In do.sh line 2:
while read i; do printf "\n"; done < target_files_list.txt
      ^-- SC2162: read without -r will mangle backslashes.

したがって、次のようになります。

$ while read -r i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt

Ubuntu
  1. ファイル内の文字列を置き換える方法は?

  2. SedまたはExを使用してブロック(複数行コード)を新しいテキストブロック(コード)に置き換える方法は?

  3. 改行をNulに置き換えますか?

  1. sed のようなテキストを python に置き換えるにはどうすればよいですか?

  2. Linuxコマンドラインで複数のファイルの文字列を置き換える方法

  3. Linuxでjar内のファイルをコマンドラインに置き換える方法は?

  1. スマートクォートをLinuxsedコマンドに置き換えます

  2. sedを使用してコマンドラインでテキストを操作する

  3. 複数行にわたる SED 置換