Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace newline character in bash variable?

I am trying to understand the "cdargs-bash.sh" script with cdargs packages. And I have a question about in the following function:

function _cdargs_get_dir () { local bookmark extrapath # if there is one exact match (possibly with extra path info after it), # then just use that match without calling cdargs if [ -e "$HOME/.cdargs" ]; then     dir=`/bin/grep "^$1 " "$HOME/.cdargs"`     if [ -z "$dir" ]; then         bookmark="${1/\/*/}"         if [ "$bookmark" != "$1" ]; then             dir=`/bin/grep "^$bookmark " "$HOME/.cdargs"`             extrapath=`echo "$1" | /bin/sed 's#^[^/]*/#/#'`         fi     fi     [ -n "$dir" ] && dir=`echo "$dir" | /bin/sed 's/^[^ ]* //'` fi if [ -z "$dir" -o "$dir" != "${dir/ /}" ]; then     # okay, we need cdargs to resolve this one.     # note: intentionally retain any extra path to add back to selection.     dir=     if cdargs --noresolve "${1/\/*/}"; then         dir=`cat "$HOME/.cdargsresult"`         /bin/rm -f "$HOME/.cdargsresult";     fi fi if [ -z "$dir" ]; then     echo "Aborted: no directory selected" >&2     return 1 fi [ -n "$extrapath" ] && dir="$dir$extrapath" if [ ! -d "$dir" ]; then     echo "Failed: no such directory '$dir'" >&2     return 2 fi 

}

What's the purpose of the testing:

"$dir" != "${dir/ /}" 

Here the testing span over two lines; does it want to remove the newline character in $dir or maybe for some other reason? I am just starting to learn bash scripting and I have Googled some time but couldn't find any usage like this.

like image 469
yorua007 Avatar asked Aug 28 '11 03:08

yorua007


People also ask

How do I replace a string with a new line?

If you're trying to replace the literal string "\r\n" with an actual new line I had to do the following: set search mode to normal, find/replace \r\n with ***. Then set search mode to Extended, find/replace *** with \r\n.

How can I replace a newline (\ n using SED?

Using `sed` to replace \n with a comma By default, every line ends with \n when creating a file. The `sed` command can easily split on \n and replace the newline with any character. Another delimiter can be used in place of \n, but only when GNU sed is used.

What is new line character in bash?

The newline character is denoted as “\n”. Using both the echo and printf commands, we can print strings with new lines in them.


1 Answers

Yes you are right, it removes the newline character. I think the purpose of the test is to make sure $dir doesn't contain multiple lines.

Alternatively, you can remove \newline by

${dir/$'\n'/} 

This doesn't require two lines so I think it looks better.

like image 129
Mu Qiao Avatar answered Sep 18 '22 19:09

Mu Qiao