Ken's Lotto Syndicate

Powerball Syndicate Home Page

Site Tools


sed

Differences

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

Link to this comparison view

Next revision
Previous revision
sed [2025/07/01 00:36] – created kensed [2026/07/07 23:13] (current) – external edit 127.0.0.1
Line 1: Line 1:
 ===== sed ===== ===== sed =====
-Replacing multiple strings with sed+==== Replacing multiple strings with sed ==== 
  
 While I'm the guy that effectively lives on the command-line, I still rarely use sed. As I've been trying to use it more, I've run into some gotchas, mostly around the regular expression syntax and doing multiple replacements at one time. While I'm the guy that effectively lives on the command-line, I still rarely use sed. As I've been trying to use it more, I've run into some gotchas, mostly around the regular expression syntax and doing multiple replacements at one time.
Line 14: Line 15:
 sed --in-place='.bak' 's/\(first\|second\)/next/g' /tmp/some-file sed --in-place='.bak' 's/\(first\|second\)/next/g' /tmp/some-file
 </code> </code>
 +\\
 +\\
 +\\
 +===== To find a line matching a specific pattern in a file, and append a value to the end of that line in Bash. =====
 +
 +The general syntax for this operation is:\\
 +<code>
 +sed -i '/pattern/ s/$/value_to_append/' filename
 +</code>
 +Explanation:
 +
 +    sed -i:\\
 +    This option enables in-place editing, meaning the changes are directly applied to the original filename. If you want to see the changes before modifying the file, remove -i to print the output to standard output.\\
 +    /pattern/:\\
 +    This specifies the regular expression pattern to search for within each line. Only lines matching this pattern will be affected.
 +    s/$/value_to_append/:\\
 +    This is the substitution command:\\
 +        s: Indicates a substitution operation.\\
 +        $: This is a special regular expression character that matches the end of a line.\\
 +        value_to_append: This is the text or value you want to add to the end of the matched line.\\
 +\\
 +Example:\\
 +To find lines containing "example_string" in my_file.txt and append "_NEW" to the end of those lines:\\
 +<code>
 +sed -i '/example_string/ s/$/_NEW/' my_file.txt
 +</code>
 +Using a variable for the value to append:\\
 +You can also use a shell variable to store the value you want to append:\\
 +<code>
 +append_value="_ADDITION"
 +sed -i "/example_string/ s/\$/${append_value}/" my_file.txt
 +</code>
 +\\
 +Note: When using variables in the substitution part of sed, it's important to use double quotes around the sed command to allow for variable expansion.\\
 +Also, the $ in s/$/ needs to be escaped with a backslash (\$) when using double quotes to prevent the shell from interpreting it as a variable.\\
  
sed.1751330180.txt.gz · Last modified: (external edit)