User Tools

Site Tools


file:replace_all_occurrences_of_string_within_a_file

This is an old revision of the document!


File - Replace all occurrences of string within a file

Change all references of the word dog to cat in the file:

sed -e 's/dog/cat/g' filename

This uses sed to stream edit files, which means change them on the fly.

# See more examples here http://www.pantz.org/software/shell/shelloneliners.html

Find and replace “dog” or “cat” or “bird” with “pet” on every line and print it out.

awk '{gsub(/dog|cat|bird,"pet");print}' filename

Find and replace “dog” with “cat” in every file with extension txt.

awk '{gsub("dog", "cat", $0); print > FILENAME}' *.txt

Find every line that begins with cat. In that line replace furry with nothing. Change the file called filename inline (-i).

sed -i '/^cat/{s/furry//}' filename

Find cat by itself on it's own line even if there are spaces or tabs before it or after it. Replace it with dog. Then print the line.

awk '{sub(/^[ \t]*cat .*$/,"dog");print}' filename

Find any line starting with the defined shell variable SHELLVAR (notice ' ' around it so it's evaluated). When the line is found substitute in foo or boo or coo with bar. Edit the file inline.

sed -i '/^'${SHELLVAR}'/s/\(foo\|boo\|coo\)/bar/' filename
file/replace_all_occurrences_of_string_within_a_file.1468171568.txt.gz · Last modified: 2020/07/15 09:30 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki