变量替换与扩展

掌握Shell脚本:变量扩展与进程替换的高级技巧 本文深入探讨了在Shell脚本中变量扩展和进程替换的高级技巧。通过具体的例子,展示了如何在不同场景下使用变量扩展来实现复杂的命令行操作,以及如何利用进程替换来简化数据处理流程。同时,文章还涵盖了如何通过自定义函数和别名来提高工作效率,以及如何配置Shell环境以适应个人喜好和特定任务的需求。 阅读详情
一、变量替换

${varname:-word}    如果变量varname存在且非null,则返回其值,否则,返回word
${varname-word}      如果变量varname存在,则返回其值,否则,返回word

$ var=
$ echo ${var:-"hello"}
hello
$ echo ${var-"hello"}

$ unset var
$ echo ${var-"hello"}
hello
$


${varname:+word}    如果变量varname存在且非null,则返回word,否则,返回null ${varname:=word}   如果变量varname存在且非null,则返回其值,否则,设置它为word,并返回word

$ var=
$ echo ${var:="hello"}
hello

$ echo ${var}

hello

$ var=

$ echo ${var="hello"}

$
echo ${var}


$


${varname:?word}   如果变量varname存在且非null,则返回其值,否则,显示varname:word,并退出当前的命令或脚本,省略word会出现默认的信息parameter null or not set。
${varname?word}      如果变量varname存在, 则返回其值, 否则,显示varname:word,并退出当前的命令或脚本,省略word会出现默认的信息parameter null or not set。

$ var=
$ echo ${var:?"hello"}
bash: var: hello
$ echo ${var?"hello"}

$ unset var
$ echo ${var?"hello"}
bash: var: hello
$


二、模式匹配运算

(注意:这里用的模式都是通配字符模式,而非正则表达式)

假设变量 path=/home/tolstoy/mem/long.file.name

${variable#pattern}      如果模式匹配于变量的开头处,则删除匹配的最短部分,并且返回剩下的部分

例如:${path#/*/}        结果: tolstoy/mem/long.file.name

${variable##parttern}  如果模式匹配于变量的开头处,则删除匹配的最长部分,并且返回剩下的部分

例如:${path##/*/}        结果: long.file.name

${variable%parttern}    如果模式匹配于变量的结尾处,则删除匹配的最短部分,并且返回剩下的部分

例如:${path%.*}           结果: /home/tolstoy/mem/long.file

${variable%%parttern} 如果模式匹配于变量的结尾处,则删除匹配的最长部分,并且返回剩下的部分

例如:${path%%.*}        结果: /home/tolstoy/mem/long

${varname=word}      如果变量varname存在, 则返回其值,否则,设置它为word,并返回word ${varname+word}      如果变量varname存在,则返回word,否则,返回null

$ var=
$ echo ${var:+"hello"}

$ echo ${var+"hello"}
hello
$ unset var
$ echo ${var+"hello"}

$


三、特殊情况

${#var}  表示字符串长度

$#  ${#*} ${#@} 表示位置参数的个

对于数组来说,${#array_name} 表示的是数组中第一个元素的长度
对于数组来说,${#array_name[*]}和${#array_name[@]}表示数组中元素的个数
word读取并替换内容(table与变量都可替换) 读取word稳定并进行内容替换,table与其余变量都可进行替换,程序可以直接导入运行,jar都带着 立即下载

相关推荐

java替换word中的变量

java替换word字符串 附带jar;支持docx,doc

变量替换扩展

变量替换扩展: 功能 表达式 说明 使用默认值 ${var:-word} var存在且非空,则值为$var;若var未定义或为空值,则值为word,但var的值不变 赋予默认值 ${var:=word} var存在且非空,则值为$var;若var未定义或为空值,则值为word,且var被赋值word 非空或未定义报错 ${var:?

Ash_DMY的博客 655

手把手教你用Matlab为PMSM电流环设计2P2Z补偿器(附与PI对比)

本文详细介绍了如何使用Matlab的controlSystemDesigner工具为永磁同步电机(PMSM)电流环设计2P2Z补偿器,并与传统PI控制器进行性能对比。通过频域分析和时域仿真,展示了2P2Z补偿器在提升带宽、减少超调等方面的优势,为高性能伺服驱动和精密运动控制提供了实用解决方案。

weixin_42551227的博客 379

Java-POI替换Word模板文档中的变量,生成Word文档

第一步:在项目中导入POI的jar包,以及相关的jar包。 所需的jar包列表: 下载地址:http://download.youkuaiyun.com/download/qq_34908167/10046670 第二步:建立util工具类。 public class DocxUtil{ /** * @Description: 将t中的字段转换成替换模板需要的数据${字...

象话的博客 1万+

内网开发必备:5分钟搞定WSL2离线安装(含Ubuntu迁移避坑指南)

本文详细介绍了在内网环境下快速完成WSL2离线安装的完整流程,包括系统兼容性检查、Linux内核更新包安装以及Ubuntu镜像的离线部署。特别针对外网Ubuntu环境迁移至内网时的用户权限、系统路径等常见问题提供了实用解决方案,帮助开发者高效搭建Linux开发环境。

weixin_29255731的博客 402

vins-mono保存、重载地图、evo工具测试

下面咱们来对vins-mono的重定位vins-mono官方源码地址:https://github.com/HKUST-Aerial-Robotics/VINS-Mono https://blog.youkuaiyun.com/learning_tortosie/article/details/83182258 运行这条: roslaunch benchmark_publisher publish.launc...

追 1万+

shell 变量替换与扩展

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34362991的博客 222

【RT-DETR涨点改进】小目标检测、特征融合改进篇 | TGRS 2024 | RT-DETR引入CSFM上下文选择融合模块,适合多模态检测、红外小目标检测、小目标检测、遥感目标检测等任务有效涨点

本文提出了一种改进RT-DETR目标检测模型的方法,通过引入上下文选择融合模块(CSFM)显著提升复杂背景下小目标和低对比度目标的检测精度。CSFM模块采用多尺度特征融合和动态特征选择机制,有效增强模型的全局上下文感知能力,同时保留细节特征。该模块通过通道减少机制和空间信息调节,实现从粗到细的特征聚合,减少误报并提高轮廓检测精度。实验表明,改进后的RT-DETR模型在多个基准测试中表现优异,计算效率与检测精度均优于现有方法。文章还详细介绍了模块配置和yaml文件修改方法,为模型部署提供指导。

Ai缝合怪、助力小伙伴高效发论文 1724

Shell中的命令替换及变量扩展

命令替换 命令替换就是在SHELL 内嵌套多条命令,一次性执行得到结果。 一层Shell嵌套 echo `whoami` whoami echo $(whoami) root echo "hello,`whoami`" hello,root echo "hello,$(whoami)" hello,root ...

锋子 790

深度学习时间序列预测:GRU算法构建多变量时间序列预测模型+代码实战

深度学习多变量时间序列预测:GRU算法构建多变量时间序列预测模型+代码实战 注意参考:深度学习多变量时间序列预测:GRU算法构建单变量时间序列预测模型+代码实战 GRU(Gate Recurrent Unit)是循环神经网络(Recurrent Neural Network, RNN)的一种。和LSTM(Long-Short Term Memory)一样,也是为了解决长期记忆和反向传播中的梯度等问题而提出来的。 GRU和LSTM在很多情况下实际表现上相差无几,那么为什么我们要使用新人GRU(.

data+scenario+science+insight 4033

使用 Simulink 和 Simscape Electrical 工具箱设计一个 Buck 转换器系统

Buck 转换器(降压转换器)是一种常用的 DC-DC 转换器,用于将较高的输入电压转换为较低的输出电压。为了评估其抗干扰能力,我们可以在模型中引入不同的干扰源,并观察系统的响应情况。电网电压波动:输入电压的变化。负载突变:负载电阻或电感的变化。电磁干扰:高频噪声或脉冲干扰。通过模拟这些干扰,我们可以分析系统的动态响应特性,并采取相应的措施来提高系统的抗干扰能力。

xiaoheshang_123的博客 378

shell中变量替换与/或扩展(二)

${#var} 字符串长度(即变量$var的字符个数)。对于数组来说,${#array}是数组的第一个元素的升序. ${var#Pattern}, ${var##Pattern} 删除从$var前端开始的最短或最长匹配$Pattern的字符串。

2301_78384345的博客 1184

微信小程序云开发 - 实现商家转账到零钱(微信企业付款到零钱) V3功能流程及完整实例代码,过微信云开发的云函数实现企业付款到零钱(提供详细示例源码纯云函数实现,证书、密钥、签名等各种常见问题解决方案

企业付款到零钱(微信小程序提现功能,提现到零钱)微信小程序-云函数实现微信企业付款到零钱功能,实现微信商户号中的企业付款到零钱的功能,微信小程序+云开发+商家转账至零钱+微信小程序用户提现,使用云开发环境的云函数实现微信小程序的支付功能,微信小程序实现微信企业付款到零钱功能的流程,V3 V2基于微信云开发的商家转账至零钱,小程序云函数企业付款到零钱功能实现,云开发实现微信商户支付企业付款到零钱功能,不用服务器纯云函数实现,详细示例代码demo教程,API证书错误,转账不到账怎么办,密钥生成有误,转账失败,有

🏆 前端领域优质创作者 1万+

shell中变量扩展/子串替换(三)

${var:pos} 变量var被展开成从位移pos个字符往后的值. ${var:pos:len} 从变量var中展开成从位移pos的字符往后最长为len的字符串。 ${var/Pattern/Replacement} 在变量var第一个匹配Pattern的字符串用Replacement代替. 如果省略了Replacement ,则第一个匹配Pattern的字符串会被删除. ${var//Pattern/Replacement}

2301_78384345的博客 596

ATT MTU 交换机制:提升 BLE 数据传输效率的关键

在低功耗蓝牙(BLE)技术的面试中,ATT MTU 交换机制始终是高频考点。无论是芯片厂商的固件开发岗,还是物联网设备的协议栈调试岗,面试官都爱通过这个知识点考察候选人对 BLE 数据传输底层逻辑的理解。本文将系统梳理核心考点,结合历年真题详解应答思路,轻松应对这类问题。​

byte轻骑兵的技术小窝 2411

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

utshell变量扩展系统:参数替换与命令替换深度解析

前往项目官网免费下载:[https://ar.openeuler.org/ar/](https://ar.openeuler.org/ar/?utm_source=csdn_blog) utshell作为openEuler系统中的重要shell工具,兼容Bourne shell并融合了Korn shell与C shell的强大特性,其变量扩展系统是实现命令行高效操作的核心功能之一。本文将带您深入

gitblog_06861的博客 129

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

归因分析【三】:维度归因实战与变量替换扩展

大家好,欢迎来到归因分析系列的第三篇,在本文中,我们将首先给出一个应用维度归因的案例,然后再讨论一下其他的变量替换的变体方法。以便大家能够真正在实践中,应用掌握差分法分析出更重要的业务维度或者因子。你的鼓励是我最大的创造动力。

qq_22208399的专栏 1184

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

shell变量替换扩展——变量测试

转载于:https://www.cnblogs.com/niezhongle/p/11283065.html

157

env-cmd 环境变量扩展:如何在命令行中动态替换 $var 值

env-cmd 是一款强大的命令行工具,它允许开发者从文件中加载环境变量并在命令执行时动态替换 `$var` 和 `${var}` 格式的变量引用。本文将详细介绍如何使用 env-cmd 的环境变量扩展功能,让你的命令行操作更加灵活高效。 ## 🌟 核心功能:动态变量替换 env-cmd 的核心能力在于其环境变量扩展机制,通过 `--expand-envs` 选项启用后,工具会自动扫描命令及

gitblog_00607的博客 411

shell 变量替换扩展字符串替换

转载于:https://www.cnblogs.com/niezhongle/p/11283105.html

138

php 宏变量替换,【PHP扩展开发】PHP_FE 宏替换

PHP_FE宏替换过程:PHP扩展研究之 PHP_FE 宏替换过程:// zend函数入口const zend_function_entry helloworld_functions[] = {// PHP_FE(array_max,NULL) // 此处和下面写法效果相等{"array_max",zif_array_max,NULL,(zend_uint)(sizeof(NULL) / siz...

weixin_30273263的博客 231

字符串变量替换扩展举例

转载于:https://www.cnblogs.com/niezhongle/p/11283097.html

162

shell 基本语法第一讲之(变量的使用、文件名替换和参数扩展、命令代换、算术代换、单引号、双引号)

shell 基本语法第一讲之(变量的使用、文件名替换和参数扩展、命令代换、算术代换、单引号、双引号)

有一种信仰叫海阔天空 824

【BASH】完全版本的 bash 变量替换

总结关于BASH中变量的内部替换备忘

躬行纸上浅知 2021

bash中输出特定变量名的内容,属于 参数替换和扩展 这一章节

<br />写出来还真简单。<br />这样我运行,<br />./script.sh v1就能输出 var1<br /> <br /><br />#!/bin/sh<br /> <br />v1="var1"<br /> <br />vt=$1<br /> <br />echo ${!vt}<br /> <br /> <br />其他复杂的有待学习。

RichardYSteven的专栏 1450
上一篇: 引用及虚函数
下一篇: 显示目录结构的shell脚本
LoveDisc
博客等级 码龄16年 0粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值