Why is my csh script not working with special characters?

2.6k Views Asked by At
#!/bin/csh -f

foreach line ("`cat test`")
    set x=`echo "$line" | awk '{split($0, b, " "); print b[1]}'`
    echo "$x"
end

test file contains following contents:

How to Format
Stack[7] Overflow
Put returns between paragraphs

On executing the script I am getting following error:

set: No match.

How to store the string which contains special character like square brackets [] in a variable and then use them in code?

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is that you're doing:

set x = [some string with shell globbing characters]

This won't work for the same reason that set x = foo works, but set x = [foo] doesn't. You need to use set x = "[foo]" (or '[foo]') to escape the special shell globbing characters ([ and ] in this case).

Nesting quotes in the C shell is pretty hard, and it's one the reasons it's generally discouraged to use the C shell for scripting. It's perhaps possible for your command, but I'm not smart enough (or too lazy) to figure out how. My solution is typically to set the special noglob variable to prevent expansion of globbing characters:

set noglob
foreach line ("`cat test`")
    set x = `echo "$line" | awk '{split($0, b, " "); print b[1]}'`
    echo "$x"
end

outputs:

How
Stack[7]
Put

P.S. There is an easier way to echo the first word of every line; put it in a list:

set noglob
foreach line ("`cat test`")
    set x = ($line)
    echo "$x[1]"
end