0

I have an sed command line which replaces ASCII 1 with |:

sed -e 's/^A/\|/g' file_name

and this works. However, when I put it in a function in my bash file:

func(){
    sed -e 's/^A/\|/g'
}

it doesn't work:

func file_name

just hangs, instead of displaying the file.

Have I made a mistake? I opened a new terminal so my bash was definitely loaded.

2
  • 1
    You got your answer, but I'd like to add that you don't need to escape | with a backslash. It doesn't have a special meaning in the replacement string. The superfluous backslash will usually do no harm, but \| is undefined, so future versions of sed could give it some unwanted meaning.
    – Philippos
    Commented Nov 16, 2017 at 12:08
  • @Philippos Quite insightful for such a subtlety. :)
    – B Layer
    Commented Nov 16, 2017 at 14:20

2 Answers 2

2

You have to process file_name as an input parameter it doesn't just magically get applied to commands in the function...

func() {
    sed -e 's/^A/\|/g' "$1"
}

First parameter passed is stored in $1, second in $2, and so on.

This would work with your version, BTW: func < file_name

2

It doesn't actually hang. It waits for input :-)

Either you do this

func() # replace something in the file, i.e. modify it
{
    sed -e 's/^A/\|/g' -i "$1"
}

or this

func() # output the contents of the file to console after applying sed
{
    sed -e 's/^A/\|/g' < "$1"
}

Also bash/POSIX shell are not C.

You must log in to answer this question.

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