Help with tr


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Help with tr
# 1  
Old 04-03-2013
Help with tr

Hi,

I have file as follows:

Input:
Quote:
abc
def
ghi
Output:
Quote:
abc|def|ghi|
Required output:
Quote:
abc|def|ghi
Code:
Code:
 
tr '\n' '|' < ${TEMPDIR}/in.txt > ${TEMPDIR}/out.txt

Help is appreciated to fix code to remove the last pipe.
# 2  
Old 04-03-2013
If you are running ksh, you could do the following:-
Code:
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
# 3  
Old 04-03-2013
Using awk program:
Code:
awk ' {
        A[++r] = $0
}
END {
        for (i = 1; i <= r; i++) {
                printf i == r ? A[i] : (A[i] "|")
        }
        printf "\n"
} ' file

# 4  
Old 04-03-2013
Try:
Code:
paste -sd \| in.txt

These 2 Users Gave Thanks to Scrutinizer For This Post:
# 5  
Old 04-03-2013
A much simpler awk approach:
Code:
awk '$1=$1' RS= OFS="|" file

# 6  
Old 04-03-2013
@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:
Code:
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..

Last edited by Scrutinizer; 04-03-2013 at 04:52 PM..
This User Gave Thanks to Scrutinizer For This Post:
# 7  
Old 04-03-2013
Quote:
I have file as follows:

abc
def
ghi
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?
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question