0

How do I only show the output of /var/www/html/index.html from the file called file.pp as shown below:

file {'/var/www/html/index.html':
  ensure  => 'file',
  content => "Hello World!\n",
}

So far I can only get it to show the output '/var/www/html/index.html': by using the command

cat file.pp | grep file | awk -F '{' '{print $2}'

I only want it to show /var/www/html/index.html

LinuxPingu
  • 89
  • 3
  • 13
  • There are 2 occurrences of `file` in the snippet you posted, do you always want to retrieve the first line? – Arkadiusz Drabczyk Sep 26 '20 at 16:17
  • try with `cat file.pp | grep file | awk -F '{' '{print $2}' | cut -d: -f1` – redInk Sep 26 '20 at 16:23
  • 2
    based solely on the (simple) sample input and the OPs test code: `awk -F"'" '/^file/ {print $2}' file.pp` => use a single quote as the input field separator, and then for any line that starts with `^file` print the 2nd field; keep in mind this will generate multiple lines of output if there are multiple lines that start with `^file`; this also assumes the desired field is always on the same line with `^file` and always wrapped in a pair of single quotes – markp-fuso Sep 26 '20 at 16:25
  • @redInk I am afraid that command is still showing the output that has single quotes in – LinuxPingu Sep 26 '20 at 16:38

1 Answers1

2

With sed

sed -n "s/^file.*'\(.*\)'.*$/\1/ p" file

Use double quotes around the command's body, that is convenient because we look for single quotes in the text. Enclose into parentheses the part to extract, which is just between single quotes. At the replacement part we reference this part as \1, that is the first and only pattern we have matched with () and we print only this. -n means no printing of lines and the final p means print only the matched and substituted line.


Or with awk (as suggested already by @markp-fuso), use the quote as separator and print second field when matching the line beginning:

awk -F"'" '/^file/{print $2}' file
thanasisp
  • 5,855
  • 3
  • 14
  • 31
  • Thank you @thanasisp. Can you explain what the 1 does? Does 1 mean the first occurance and does $ mean the end of the line? – LinuxPingu Sep 26 '20 at 17:21
  • 1
    Kev see this: https://www.grymoire.com/Unix/Sed.html#uh-4 In the first part we put parentheses around parts and at the replacement parts we access them as `\1`, `\2` etc. So `\1` here just means the first and only part we had inside `()` – thanasisp Sep 26 '20 at 17:23
  • Just to let people know that there is another waay you can achieve this by using: ````cat file.pp | awk -F "'" 'NR==1{print $2}'```` – LinuxPingu Sep 26 '20 at 22:37
  • That's called a [useless `cat`.](https://stackoverflow.com/questions/11710552/useless-use-of-cat) – tripleee Sep 30 '20 at 05:36