3

The following two sed commands works.

sed -E "s#Example(.*)#\nconst ex='Example\1';\n#; s#Input:(.*)#const\1;#" in.txt | sed '/\S/!d'

However, how to rewrite them so that only one sed command is used? i.e.

sed -E "???" in.txt 

I tried this but it did not work:

sed -E "s#Example(.*)#\nconst ex='Example\1';\n#; s#Input:(.*)#const\1;#; /\S/!d" in.txt

in.txt:

Example 1:



Input: s = "()"

GNU sed version is 4.7.

Expected output:

const ex='Example 1:';
const s = "()";
3
  • Input is a text file. The second sed command is to remove the empty lines. Commented Sep 5 at 1:32
  • 1
    what's supposed to happen with a line like AnotherExample Input "10" ? Commented Sep 5 at 3:43
  • @ jhnc, Good question. Assume that line does not occur. Commented Sep 6 at 0:21

2 Answers 2

1

You are inserting line breaks into the pattern buffer, and the pattern buffer then has a multiline string in it. The /\S/!d command will not match a pattern buffer that contains a nonempty line with empty lines, so it will not delete empty lines from your multiline strings.

Fix is simple:

$ sed -E 's#Example(.*)#const ex='Example\1';#; s#Input:(.*)#const\1;#; /\S/!d' in.txt
const ex=Example1;
const s = "()";

... just don't add \n... sed is going to preserve those line breaks from the original line when you do s### substitution. You don't need to add more.

Also, in my shell ! was expanded inside double quotes, so I switched to single quotes.

Sign up to request clarification or add additional context in comments.

Comments

0

I dunno with sed (line oriented), but with :

awk '
    $1=="Example"{print "const ex=\047Example "$2"\047"}
    $1=="Input:"{sub(/Input:/, "const ");print}
' file

Output:

const ex='Example 1:'
const  s = "()"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.