User Tools

Site Tools


ubuntu:file:replace_all_occurrences_of_string_within_a_file

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
ubuntu:file:replace_all_occurrences_of_string_within_a_file [2020/02/13 23:39] peterubuntu:file:replace_all_occurrences_of_string_within_a_file [2022/06/13 11:38] (current) – removed peter
Line 1: Line 1:
-====== Ubuntu - File - Replace all occurrences of string within a file ====== 
- 
-===== Using awk ===== 
- 
-Find and replace "dog" or "cat" or "bird" with "pet" on every line and print it out. 
- 
-<code bash> 
-awk '{gsub(/dog|cat|bird,"pet");print}' filename 
-</code> 
- 
- 
-Find and replace "dog" with "cat" in every file with extension txt. 
- 
-<code bash> 
-awk '{gsub("dog", "cat", $0); print > FILENAME}' *.txt 
-</code> 
- 
- 
-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. 
- 
-<code bash> 
-awk '{sub(/^[ \t]*cat .*$/,"dog");print}' filename 
-</code> 
- 
- 
-Substitute "dog" with "cat" on lines that don't contain the word "pet". 
- 
-<code bash> 
-awk '!/pet/{gsub(/dog/, "cat")};{print}' filename 
-</code> 
- 
----- 
- 
-===== Using sed ===== 
- 
-Change all references of the word dog to cat in the file: 
- 
-<code bash> 
-sed -e 's/dog/cat/g' filename 
-</code> 
- 
-This uses **sed** to stream edit files, which means change them on the fly. 
- 
- 
-Find every line that begins with cat.  In that line replace furry with nothing.  Change the file called filename inline (-i). 
- 
-<code bash> 
-sed -i '/^cat/{s/furry//}' filename 
-</code> 
- 
- 
- 
-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. 
- 
-<code bash> 
-sed -i '/^'${SHELLVAR}'/s/\(foo\|boo\|coo\)/bar/' filename 
-</code> 
- 
- 
- 
-Replace spaces in a file with hyphens 
- 
-<code bash> 
-sed -i 's/ /-/g' * 
-</code> 
  
ubuntu/file/replace_all_occurrences_of_string_within_a_file.1581637186.txt.gz · Last modified: 2020/07/15 09:30 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki