0

I am trying to replace a range of text with sed containing special characters.

I have the following output:

"Users" "/Users/Users"   SERVER1
"Roaming Profiles" "/Roaming Profiles/Roaming Profiles"   SERVER2

I would like it to be like this:

Users SERVER1
Roaming Profiles SERVER2
1
$ sed -r 's/"([^"]*)"([^"]*"){2}[[:space:]]*/\1 /' file
Users SERVER1
Roaming Profiles SERVER2

How it works

The sed substitution command has the form s/old/new/. The regular expression for old has the following parts:

  • "([^"]*)" -- This matches the first string in quotes and saves it in group 1.

  • ([^"]*"){2} -- This matches the second quoted string (including the spaces which precede it).

  • [[:space:]]* -- This matches the spaces which follow the second quoted string.

The regular expression for new is simply \1 which is a space followed by the first quoted string which, via the parenthesis, we had saved in group 1.

Mac OSX or other BSD platforms

On OSX, try:

sed -E 's/"([^"]*)"([^"]*"){2}[[:space:]]*/\1 /' file
1

Using Awk:

awk -F\" '{print $2,$5}' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.