2

I have this simple script:

#!/bin/bash

# This command removes the last "\n" (line feed) character from the file specified as parameter
#
# Params:
# $1 [FILE_NAME] - the name of the file to trim

if [ "$1" = "" ]; then
        echo "perlrmlastlf - A command utility which uses perl to remove the last \"\n\" (line feed) character inside a file"
        echo $'\r'
        echo "perlrmlastlf: missing FILE_NAME"
        echo "Usage: perlrmlastlf [FILE_NAME]"
        echo $'\r'
        exit;
fi

if [[ ! -f $1 ]]; then
        echo "perlrmlastlf - A command utility which uses perl to remove the last \"\n\" (line feed) character inside a file"
        echo $'\r'
        echo "perlrmlastlf: wrong FILE_NAME $1: No such file"
        echo "Usage: perlrmlastlf [FILE_NAME]"
        echo $'\r'
        exit;
fi

FILE=$1
TMP_FILE="$FILE.tmp.perlrmlastlf"
perl -0 -pe 's/\n\Z//' $FILE > $TMP_FILE

mv $TMP_FILE $FILE

Now, I can actually use it only with a valid filename as the parameter, but what if I want to make it receive the output from a pipe and use that instead of $1 [FILE_NAME]? Like this:

user:machine ~$ cat file.txt | pcregrep -o "some pattern" | perlrmlastlf
user:machine ~$ # output of `cat file.txt | pcregrep -o "some pattern"` but without last \n, if present

And make perlrmlastlf receive the pipeline output and use it and then output back to the console the matched string without the last \n char

How can I accomplish this?

1 Answer 1

2

I'm sure there's a more elegant way, but it's early...

if (( $# > 0 )); then
    # the "-i" option takes care of writing to a tmp file and 
    # overwriting the original file
    perl -0 -i -pe 's/\n\Z//' "$1"
else
    # read from stdin and write to stdout
    perl -0 -pe 's/\n\Z//'
fi

you'll need to remove the [[ $1 == "" ]] check, and put the [[ ! -f $1 ]] check inside the "true" block of my if statement.

2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .