Help with tr

Hi,

I have file as follows:

Input:

Output:

Required output:

Code:

 
tr '\n' '|' < ${TEMPDIR}/in.txt > ${TEMPDIR}/out.txt

Help is appreciated to fix code to remove the last pipe.

If you are running ksh, you could do the following:-

tmpvar=`tr '\n' '|' < ${TEMPDIR}/in.txt`
echo "${tmpvar%\|}" > $TEMPDIR/out.txt

That will chop off the last bit. There might be a neater way with awk though.

I hope that this helps,
Robin
Liverpool/Blackburn
UK

Using awk program:

awk ' {
        A[++r] = $0
}
END {
        for (i = 1; i <= r; i++) {
                printf i == r ? A : (A "|")
        }
        printf "\n"
} ' file

Try:

paste -sd \| in.txt
2 Likes

A much simpler awk approach:

awk '$1=$1' RS= OFS="|" file

@yoda, that would be problematic if there is any kind of whitespace other than the newlines. Even if you set FS to a newline, the RS= would compress multiple newlines and create multiple records.

As a work-around one could choose a character that will not occur in the text for example:

awk '{$1=$1}1' FS='\n' RS=� OFS="|"

Note that there would need to be curly braces around $1=$1 otherwise it would not print in case of 0 or whitespace in $1

But this would leave a trailing pipe symbol after the last record, so that still would not work as desired...

Also there might be record length limitations..

1 Like

Is that all there is to the input file? If so, doesn't seem like a real-world problem. What comes after those three lines, if anything?

Why not try the back door:-

#!/bin/bash

# Assume there IS a newline at the end also...
printf "abc\ndef\nghi\n" > /tmp/sometext
ls -l /tmp/sometext

# Important line, note backticks...
somestring=`cat /tmp/sometext`

# Voila trailing newline eliminated...
printf "$somestring" > /tmp/sometext
ls -l /tmp/sometext

# Now try your code, as I haven't... ;o)
Last login: Wed Apr  3 21:20:20 on ttys000
Barrys-MacBook-Pro:~ barrywalker$ ./simple_str.sh
-rw-r--r--  1 barrywalker  wheel  12  3 Apr 21:20 /tmp/sometext
-rw-r--r--  1 barrywalker  wheel  11  3 Apr 21:20 /tmp/sometext
Barrys-MacBook-Pro:~ barrywalker$ 

The code doesn't work as intended.

awk '{$1=$1}1' FS='\n' RS=^ OFS="|" aa

output:

---------- Post updated at 03:42 PM ---------- Previous update was at 03:40 PM ----------

This works. Thanks!!

@pinnacle. Glad the paste works. I am curious. What is your OS and version, where the awk snippet produced those result? AIX? There you would need:

awk '{$1=$1x}1' FS='\n' RS=^ OFS="|" file