I have a text file in which I want to replace a string with a new string, and then add or remove spaces to make them the same number of characters. For example, I want to replace
string .10
with
longer_string .10
In essence I need to replace 'string', and then have the '.10' in the correct column, regarldess of the number of characters in the replacement string.
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.
By default, when sed reads a line in the pattern space, it discards the terminating newline (\n) character. Nevertheless, we can handle multi-line strings by doing nested reads for every newline.
The `sed` command can easily split on \n and replace the newline with any character. Another delimiter can be used in place of \n, but only when GNU sed is used. When the \n is missing in the last line of the file, GNU sed can avoid printing \n. Furthermore, \n is usually added to each consecutive output of `sed`.
You could use sed
to do the replacement, and then perhaps re-align the columns with column
?
cat input.txt | sed 's/string/longer_string/g' | column -t
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With