[SOLVED] Multiline output to single line concatenation with delimiter string

Issue

I use this command to get a list of all the files that has changed in a pull-request.

git diff --name-only HEAD master

Sample output:

my/repo/file1.java
my/repo/file3.java
my/repo/file5.java

I would like to convert this output to the following:

file:my/repo/file1.java||file:my/repo/file3.java||file:my/repo/file5.java

so that I can run code analysis only on these files from IntelliJ IDEA.

What have I tried so far?

git diff --name-only HEAD master |  sed -e 's/^/file:/'  | paste -s -d "||" -

This gives me the following output:

file:my/repo/file1.java|file:my/repo/file3.java|file:my/repo/file5.java

Notice the single |.

Also, please simplify the command if possible.

Edit: None of the files will have a whitespace or a newline in the name.

Solution

You can also do it with awk

git diff --name-only HEAD master |
awk 'NR > 1 {printf("||")} {printf("file:%s",$0)} END{print ""}'

What this awk does is:

  • for all input lines but the first, output: ||
  • for all input lines, output: file: + <input line content>
  • when there’s no more input lines to read, output a newline character

remark: the END{print ""} is unrequited when you do out=$(git .. | awk ...)

Answered By – Fravadona

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.