I have multiple boards, Inside my bash script, I want to catch my root filesystem name using regex. When i do a cat /proc/cmdline
i have this :
BOOT_IMAGE=/vmlinuz-5.15.0-57-generic root=/dev/mapper/vgubuntu-root ro quiet splash vt.handoff=7
I just want to select /dev/mapper/vgubuntu-root
So far i managed to catch root=/dev/mapper/vgubuntu-root
using this command
\broot=[^ ]
CodePudding user response:
You can use your regex in sed
with a capture group:
sed -E 's~.* root=([^ ] ).*~\1~' /proc/cmdline
/dev/mapper/vgubuntu-root
Another option is to use awk
(should work in any awk
):
awk 'match($0, /root=[^ ] /) {
s = substr($0, RSTART, RLENGTH)
sub(/^[^=] =/, "", s)
print s
}' /proc/cmdline
# if your string is always 2nd field then a simpler one
awk '{sub(/^[^=] =/, "", $2); print $2}' /proc/cmdline
CodePudding user response:
1st solution: With your shown samples in GNU awk
please try following awk
code.
awk -v RS='[[:space:]] root=[^[:space:]] ' '
RT && split(RT,arr,"="){
print arr[2]
}
' Input_file
2nd solution: With GNU grep
you could try following solution, using -oP
options to enable PCRE regex in grep
and in main section of grep
using regex ^.*?[[:space:]]root=\K\S
where \K
is used for forgetting matched values till root=
and get rest of the values as required.
grep -oP '^.*?[[:space:]]root=\K\S ' Input_file
3rd solution: In case your Input_file is always same as shown samples then try this Simple awk
using field separator(s) concept.
awk -F' |root=' '{print $3}' Input_file
CodePudding user response:
Since you are using Linux, you can use a GNU grep:
grep -oP '\broot=\K\S '
where o
allows match output, and P
sets the regex engine to PCRE. See the online demo. Details:
\b
- word boundaryroot=
- a fixed string\K
- match reset operator discarding the text matched so far\S
- one or more non-whitespace chars.
CodePudding user response:
If the second field has the value, using awk you can split and check for root
awk '
{
n=split($2,a,"=")
if (n==2 && a[1]=="root"){
print a[2]
}
}
' file
Output
/dev/mapper/vgubuntu-root
Or using GNU-awk
with a capture group
awk 'match($0, /(^|\s)root=(\S )/, a) {print a[2]}' file