繁体   English   中英

使用 bash 脚本 (linux) 在文件夹中查找文件

[英]find a file in a folder using a bash script (linux)

  1. 需要在文件夹中创建一个文本文件(完成)

我使用 nano 创建一个名为 spn.txt 的文件并在其中输入一些数据。 (完毕)

4:3
5:5
1:5
3:1
4:3
4:1
  1. 创建脚本

    2.1。 要求用户输入文件夹中文本文件 (txt) 的名称

    2.2 找到txt文件

    如果没有找到文件,请用户输入文件夹中文本文件 (txt) 的名称

    2.3. 如果让文件读取文件的值并显示左侧的编号

#!/bin/bash
echo "please input file name with extension (e.g spn.txt)"
read filename

如何创建一个while命令

寻找文件名

如果在文件夹中找不到文件名,请用户输入文件名

如果找到文件名。 显示左侧的编号。

免责声明:这没有定义循环,因此可能无法回答您的问题。

这就是说,如果您需要快速管理一些用户交互,您可以尝试Zenity

#!/bin/bash

FILE=`zenity --file-selection --title="Select a File"`

case $? in
         0)
                echo "\"$FILE\" selected.";;
         1)
                echo "No file selected.";;
        -1)
                echo "An unexpected error has occurred.";;
esac

显然,您需要安装 Zenity,这可能是便携性方面的问题。 优点是您可以创建“复杂”输入 forms。 这完全取决于您的上下文。

您可以使用以下命令轻松实现此目的:

#!/bin/bash

filename=""

echo -e "\nStarting script ... You can press Ctrl+C anytime to stop program execution.\n"
    
##### Ensure the user will provide a valid file name #################    
while [[ ! -r "${filename}" ]] ; do
  echo -n "Please, enter the file name: (e.g spn.txt): "
  read filename
done

#
# At this point we have a valid filename supplied by the user
# So, prints the left values of it, using the ':' as a field delimiter
cut -d':' -f 1 ${filename}

上面使用的 cut 命令带有以下参数:

-d':' -> 将分隔符设置为 ':'

-f 1 -> 只显示字段编号 1。如果您想只显示正确的数字,可以在这里使用 -f 2,因为假设字段分隔符是字符 ':',正确的数字位于第二场。

别客气

如果您喜欢我的剧本,请不要忘记投票)

#!/bin/bash
###############################################################################################
#####   Maintainer: Vrej Abramian, Git: https://github.com/vrej-ab, vrejab@gmail.com    #######
#                                                                                             #
# *** Important Note! ***                                                                     #
# This script has: no warranties no assurance no security no guarantee.                       #
# This script is AS IS, free (not commercial), and written for testing, experimental purposes.#
# Try this script in a test environment and use it at your own risk!                          #
# Maintainer will not be held responsible for any problems of running this script.            #
# *** *** *** *** *** ***                                                                     #
###############################################################################################
### Configuration Parameters Start ###
request_filename_message="Please input file name with extension (e.g spn.txt): "
filename_variable='filename'
attempts_count='3'
_file_check='' # Leave this empty
### Configuration Parameters End ###

### Finctions Start ###
# Unified messages
echo_green(){ echo -en "\033[0;32m$*" ;echo -e "\033[0;0m"; }
echo_yellow(){ echo -en "\033[1;33m$*" ;echo -e "\033[0;0m"; }
echo_red(){ echo -en "\033[0;31m$*" ;echo -e "\033[0;0m"; }

# Promt and request to input a valid `filename`
request_filename_function(){
  # Use `read` with `-p` option which will prompt your message and 
  # avoid using extra `echo` command.
  read -p "${request_filename_message}" "${filename_variable}"
}

# Check if the inputed filename is accessible
file_check(){
  if [ -r "${!filename_variable}" ] ;then
    echo_green "\n[INFO]: ${!filename_variable} - file is available."
    _file_check='pass'
  else
    echo_red "\n[ERROR]: ${!filename_variable} - file is either un-available or un-accessible."
    _file_check='fail'
  fi
}

# If provided `filename` wouldn't be available, this provides retrying chances
retry_function(){
  local i=1
  while [ "${_file_check}" != 'pass' ] && [ ${i} -lt ${attempts_count} ] ;do
    echo_yellow "\n[WARN]: Please tray again - $(( attempts_count-i )) times left!"
    local i=$(( ++i ))
    request_filename_function
    file_check
  done
  if [ ${i} -gt ${attempts_count} ] ;then
    echo_red "[FATAL]: No more attempts, Bye-Bye...\n"
    exit 1
  fi
}

# Get the provided file's first column data - assuming that the delimiter is a ':' character in the file
left_handside_numbers_function(){
  cat "${1}" | awk -F':' '{print $1}'
}

# Filter the user defined param,eters in this script
defined_parameters_function(){
  defined_parameters=$(sed -n '/^### Configuration Parameters Start ###/,/^### Configuration Parameters End ###/p' "${0}" | \
          grep -v '^\#' | awk -F'=' '{print $1}')
  defined_parameters="${filename_variable} ${defined_parameters}"
}

# Run cleanup jobs
cleanup_function(){
  unset ${defined_parameters}
}
### Functions End ###

### Script Body Start ###
request_filename_function
file_check
retry_function
left_handside_numbers_function "${!filename_variable}"
defined_parameters_function
cleanup_function
### Script Body End ###

# Do not remove or comment the bellow line: exit 0
exit 0

# Do not add anything below this line!
# Additional infos
# Created at: Fri Sep  2 18:46:02 +04 2022

#   Tested in:  #
# bash --version
GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

# cat /etc/*release* 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=20.04
DISTRIB_CODENAME=focal
DISTRIB_DESCRIPTION="Ubuntu 20.04.4 LTS"
NAME="Ubuntu"
VERSION="20.04.4 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.4 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal 

# uname -a
Linux Vrej-Dell-LT 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM