Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - replace string with equal number of characters

Tags:

regex

sed

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.

like image 835
Ericvb86 Avatar asked Jan 07 '16 11:01

Ericvb86


People also ask

How do you use sed to match word and perform find and replace?

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.

Does sed support multiline replacement?

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.

How can I replace a newline (\ n using sed?

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`.


1 Answers

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
like image 119
Paul Dixon Avatar answered Oct 04 '22 23:10

Paul Dixon