-2

With

awk '{ printf "%-15s %s\n", $1, $2 }' renamed | sort -V

... I get good output from the file renamed.

It looks like:

file1           file1.new

But I want to have the output changed to this:

file1           -->  file1.new

I want to add --> at position 15 in each line.

How to do that?

4
  • Try printf "%-15s--> %s\n" in awk command. Commented Nov 3, 2024 at 7:15
  • That is it, thank you! Commented Nov 3, 2024 at 7:45
  • What should happen when the input contains a $1 that's 15 or more characters long? What if either file name contains spaces? Commented Nov 3, 2024 at 15:24
  • in my case, it will never be longer than 12 characters. Commented Nov 4, 2024 at 2:41

2 Answers 2

2

The printf format string %-15s %s\n specifies that you want to output two strings delimited by a space and terminated by a newline character.

The first string should be given a width of 15 characters, and the minus sign signifies that it should be left-justified within those 15 characters (the remaining characters to the right of the string will be filled out with spaces).

To insert --> in front of the second string, after the single space, just modify the format to %-15s --> %s\n.

Example of this:

$ printf '%s\n' "one thing" "another thing" | awk '{ printf "%-15s %s\n", $1, $2 }'
one             thing
another         thing
$ printf '%s\n' "one thing" "another thing" | awk '{ printf "%-15s -->  %s\n", $1, $2 }'
one             -->  thing
another         -->  thing

Note that the --> is actually added at position 17, not 15. Position 15 is reserved for the first string while position 16 will have that space character in the formatting string. To add --> at position 15, you would need to reduce the space for the first string to 13: %-13s --> %s\n.

0
2

Consider using column to determine the appropriate first field width instead of hard-coding 15 so it can handle fields longer than 15 chars if necessary, e.g. using any version of column:

$ cat renamed
file1 file1.new
12345678951234567890 file2.new

$ column -t renamed
file1                 file1.new
12345678951234567890  file2.new

$ column -t renamed | sed 's/  */&-->  /'
file1                 -->  file1.new
12345678951234567890  -->  file2.new

If you have GNU column then it has a -o option to specify the output field separator so then you don't need the pipe to sed:

$ column -t -o '  -->  ' renamed
file1                 -->  file1.new
12345678951234567890  -->  file2.new

It can also handle blanks inside the fields if your fields are tab-separated by adding -s$'\t' or there are all sorts of other things we could do to handle all sorts of different input, ask a new question with more details on your input format if you need more help.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.