简体   繁体   中英

What does this sed command line do?

I see this lines in my study.

$temp = 'echo $line | sed s/[a-z AZ 0-9 _]//g'
IF($temp != '')
   echo "Line contains illegal characters"

I don't understand. Isn't sed is like substituting function? In the code, [az AZ 0-9 _] should be replace with ''. I don't understand how this determines if $line has illegal characters.

sed is a stream editor tool that applies regular expressions to transform the input. The command

sed s/regex/replace/g

reads from stdin and every time it finds something matching regex , it replaces it with the contents of replace . In your case, the command

sed s/[a-z A-Z 0-9 _]//g

has [az AZ 0-9] as its regular expression and the empty string as its replacement. (Did you forget a dash between the A and the Z?) This means that anything matching the indicated regular expression gets deleted. This regular expression means "any character that's either between a and z , between A and Z , between 0 and 9 , a space, or an underscore," so this command essentially deletes any alphanumeric characters, whitespaces, or underscores from the input and dumps what's left to stdout. Testing whether the output is empty then asks whether there were any characters in there that weren't alphanumeric, spaces, or numbers, which is how the code works.

I'd recommend adding sed to the list of tools you should get a basic familiarity with, since it's a fairly common one to see on the command-line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM