Home > Back-end >  how to use cut command -f flag as reverse
how to use cut command -f flag as reverse

Time:04-12

This is a text file called a.txt

ok.google.com  
abc.google.com

I want to select every subdomain separately
cat a.txt | cut -d "." -f1 (it select ok From left side)
cat a.txt | cut -d "." -f2 (it select google from left side)

Is there any way, so I can get result from right side
cat a.txt | cut (so it can select com From right side)

CodePudding user response:

There could be few ways to do this, one way which I could think of right now could be using rev cut rev solution. Which will reverse the input by rev command and then set field separator as . and print fields as per they are from left to right(but actually they are reversed because of the use of rev), then pass this output to rev again to get it in its actual order.

rev Input_file | cut -d'.' -f 1 | rev

CodePudding user response:

Depending on what you want to do after getting the values then you could use bash for splitting your domain into an array of its components:

#!/bin/bash

IFS=. read -ra comps <<< "ok.google.com"

echo "${comps[-2]}"
# or for bash < 4.2
echo "${comps[${#comps[@]}-2]}"
google

CodePudding user response:

You can use awk to print the last field:

awk -F. '{print $NF}' a.txt

-F. sets the record separator to "."

$NF is the last field

And you can give your file directly as an argument, so you can avoid the famous "Useless use of cat"

For other fields, but counting from the last, you can use expressions as suggested in the comment by @sundeep or described in the users's guide under 4.3 Nonconstant Field Numbers. For example, to get the domain, before the TLD, you can substract 1 from the Number of Fields NF :

awk -F. '{ print $(NF-1) }' a.txt

CodePudding user response:

You might use sed with a quantifier for the grouped value repeated till the end of the string.

  • ( Start group
    • \.[^[:space:].] Match 1 dot and 1 occurrences of any char except a space or dot
  • ){1} Close the group followed by a quantifier
  • $ End of string

Example

sed -E 's/(\.[^[:space:].] ){1}$//' file

Output

ok.google
abc.google

If the quantifier is {2} the output will be

ok
abc
  • Related