How to Extract Last Field/Value from a Value Separated by backslashes in Bash (using awk)
The aim of this pageđź“ť is to explain extracting values after the last backslash in a string based on the particular example of a user-provided dataset.
- Use
awk
command in bash to extract values after the last backslash. awk
is a powerful text-processing tool in Unix/Linux.-F
option inawk
sets the field separator./
is used as the field separator in this example.$NF
inawk
represents the last field in the current record.NF
stands for Number of Fields.awk -F'/' '{print $NF}' input_file
extracts the last field from each line in a file.echo "your_data_here" | awk -F'/' '{print $NF}'
processes data directly from a variable or pipe.- Example input:
project/xyz_company/target_system/output/description:Data loader - system1
. - Example output:
description:Data loader - system1
.
User’s Code Example:
project/xyz_company/target_system/output/description:Data loader - system1
project/xyz_company/target_system/output/label:LOADER
project/xyz_company/target_system/output/last_applied_stack_version:0.1.0
project/xyz_company/target_system/output/system_account:xyz-system
project/xyz_company/target_system/output/system_callback_iam:
project/xyz_company/target_system/output/system_cloud:aws
project/xyz_company/target_system/output/system_database:datastore
project/xyz_company/target_system/output/system_folder_monitoring_stage:
project/xyz_company/target_system/output/system_folder_monitoring_stage_path:
project/xyz_company/target_system/output/system_jdbc_host:xyz-system.computing.com
project/xyz_company/target_system/output/system_region:us-west-1
project/xyz_company/target_system/output/system_role:loader_role
project/xyz_company/target_system/output/system_schema:atomic
project/xyz_company/target_system/output/system_transformed_stage:
project/xyz_company/target_system/output/system_transformed_stage_path:
project/xyz_company/target_system/output/system_username:LOADER_USER
project/xyz_company/target_system/output/system_warehouse:loader_wh
Command to Extract Values:
awk -F'/' '{print $NF}' input_file
Alternative Command for Direct Data Processing:
echo "your_data_here" | awk -F'/' '{print $NF}'
LINKS
- https://www.gnu.org/software/gawk/manual/gawk.html
- https://www.thegeekstuff.com/2010/01/awk-introduction-tutorial/
ANKI
Question: What does NF stand for in `awk`?
Answer: NF stands for Number of Fields.
Question: How do you set the field separator in `awk`?
Answer: Use the `-F` option to set the field separator.
Question: What does `$NF` represent in `awk`?
Answer: $NF represents the last field in the current record.
Question: How do you extract the last field from each line in a file using `awk`?
Answer: Use the command `awk -F'/' '{print $NF}' input_file`.
Question: How can you process data directly from a variable or pipe using `awk`?
Answer: Use the command `echo "your_data_here" | awk -F'/' '{print $NF}'.